<?php
	require_once("utils.php");
	require_once("obj/user.php");
	require_once("obj/role.php");
	$userid = $_GET["userid"];
	$user = User::getByUserId($userid);
	if(isset($_POST["btnSubmit"])){ 
		if($_POST["btnSubmit"] == "Save") {
			$user->Email = $_POST["txtEmail"];		
			$user->RoleId = $_POST["cboRole"];		
			$user->save();		
		}
		else if($_POST["btnSubmit"] == "Delete") { 
			$user->delete();
		}
		$err = error_get_last();
		if (empty($err)) {
			$u = Utils::makeUserUrl();
			header("Location:$u");
		}
	}
	
	$roles = Role::getAll();
?>

<form method="post" action="<?php echo Utils::makeUserDetailUrl($userid);?>">
	<table cellpadding="5" cellspacing="0" border="0">
		<tr>
			<td>Email:</td>
			<td><input id="txtEmail" name="txtEmail" type="text" value="<?php echo $user->Email; ?>" /></td>
		</tr>
		<tr>
			<td>Role:</td>
			<td>
				<select id="cboRole" name="cboRole">
					<option value="0">&nbsp;</option>
					<?php						
						foreach($roles as $r){
							$v = $r->RoleId;
							$n = $r->Name;
							$s = ($v == $user->RoleId) ? "selected='true'" : "";
							echo "<option value=\"$v\" $s>$n</option>";
						}
					?>
				</select>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<input name="btnSubmit" type="submit" value="Save" onclick="return validateUserDetails();" />
				<input name="btnSubmit" type="submit" value="Delete" />
				<input type="button" value="Cancel" onclick="javascript:history.back();" />
			</td>
		</tr>
	</table>
</form>

<script language="javascript" type="text/javascript">	
	function validateUserDetails() { 		
		var msg = "";
		var ok = true;		
		
		if(!validateRequired('txtEmail')) {
			msg += "Email is required\n";
			ok = false;
		}		
		else if(!validateEmail('txtEmail')) {
			msg += "Invalid email\n";
			ok = false;
		}
		
		if(!validateRequired('cboRole')) {
			msg += "Role is required\n";
			ok = false;
		}
		
		if(!ok) {
			alert(msg);
		}
		return ok;
	}
</script>